package com.emm.yixun.marketing.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.SalesGroupService;
import com.emm.yixun.basic.service.SalesGroupUserService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.enums.DataAuthorityEnums;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.SalesGroup;
import com.emm.yixun.common.model.SalesGroupUser;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.SalesGroupDto;
import com.emm.yixun.common.model.dto.SalesGroupUserDto;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.marketing.service.SalesGroupUserServiceFacade;

@Service("salesGroupUserServiceFacade")
@WebService(name = "com.emm.yixun.marketing.service.SalesGroupUserServiceFacade")
public class SalesGroupUserServiceFacadeImpl implements SalesGroupUserServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SalesGroupUserService service;

	@Autowired
	private SalesGroupService salesGroupService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private UserService userService;

	@Autowired
	private DataPermissionService dataPermissionService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private AppPushService appPushService;

	@Override
	public Response<SalesGroupUserDto> save(SalesGroupUserDto dto) {
		Response<SalesGroupUserDto> response = new Response<SalesGroupUserDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			SalesGroupUserDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(SalesGroupUserDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			SalesGroupUserDto mDto = new SalesGroupUserDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<SalesGroupUser> findById(Long id) {
		Response<SalesGroupUser> response = new Response<SalesGroupUser>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			SalesGroupUser entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<SalesGroupUser> findByDto(SalesGroupUserDto dto) {
		ResponseList<SalesGroupUser> response = new ResponseList<SalesGroupUser>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<SalesGroupUser> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<SalesGroupUser> findPageByDto(SalesGroupUserDto dto, Integer begin, Integer row) {
		Page<SalesGroupUser> response = new Page<SalesGroupUser>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<SalesGroupUser> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> batchGroupUser(User user, SalesGroupDto salesGroupDto, List<SalesGroupUserDto> userDto) {
		Response<Integer> response = new Response<Integer>();
		Project project = projectService.selectById(salesGroupDto.getProjectId());
		try {
			// 项目初始化或项目编辑
			List<SalesGroup> sgList = new ArrayList<SalesGroup>();
			SalesGroupDto sgDto = new SalesGroupDto();
			sgDto.setProjectId(salesGroupDto.getProjectId());
			sgDto.setName(salesGroupDto.getName());
			sgDto.setOrders("create_time desc");
			sgList = salesGroupService.selectListByDto(sgDto);
			if ("project".equals(salesGroupDto.getOriginal())) {
				if (null != sgList && sgList.size() > 0) {
					BeanUtils.copyProperties(sgList.get(0), salesGroupDto);
				}
			} else {
				// 新增时,判断项目组名称是否存在
				if (null == salesGroupDto.getId()) {
					if (null != sgList && sgList.size() > 0) {
						if (sgList.size() >= 0) {
							response.setSuccess(false);
							response.setResultMessage("项目下已存在名为:【" + salesGroupDto.getName() + "】的项目组名称!");
							return response;
						}
					}
				}
			}

			// 验证销售组数据是否完整
			// 无数据时,直接成功.不创建销售组
			if(null == userDto || userDto.size() == 0){
				response.setSuccess(true);
				return response;
			}
			for (SalesGroupUserDto validObj : userDto) {
				Validator validator = new Validator();
				List<ConstraintViolation> ret = validator.validate(validObj);
				if (ret != null && ret.size() > 0) {
					response.setSuccess(false);
					response.setResultMessage(ret.get(0).getMessage());
					return response;
				}
			}
			StringBuffer sb = new StringBuffer("");
			// 验证一个销售组 重复成员
			List<Long> duplicateList = removeDuplicate(userDto);
			if (duplicateList != null && duplicateList.size() > 0) {
				for (int i = 0; i < duplicateList.size(); i++) {
					User userEntity = userService.selectById(duplicateList.get(i));
					sb.append(userEntity.getUserName() + "-");
				}
				if (!StringUtils.isEmpty(sb.toString())) {
					response.setSuccess(false);
					response.setResultMessage(sb.toString() + ",存在多个!");
					return response;
				}
			}
			
			
			
			// 验证同一个用户不能在同个项目的多个销售组中
			for (SalesGroupUserDto groupDto : userDto) {
				if (groupDto.getStatus().equals("1")) { // 需要移除的数据不进行校验
					continue;
				}

				SalesGroupUserDto queryValid = new SalesGroupUserDto();
				queryValid.setAccessCode(project.getProjectCode());
				queryValid.setUserId(groupDto.getUserId());
				queryValid.setDelFlag("0");
				queryValid.setStatus("0");
				// queryValid.setSalesGroupId(dto.getId());
				List<SalesGroupUser> groupList = service.selectListByDto(queryValid);
				if (salesGroupDto.getId() == null) { // 新增
					if (groupList != null && groupList.size() > 0) {
						User userEntity = userService.selectById(groupDto.getUserId());
						sb.append(userEntity.getUserName() + ",");
					}
				} else { // 编辑
					if (groupList != null && groupList.size() > 0) {
						if (salesGroupDto.getId().compareTo(groupList.get(0).getSalesGroupId()) == 0) {
							continue;
						} else {
							if (groupList != null && groupList.size() > 0) {
								User userEntity = userService.selectById(groupDto.getUserId());
								sb.append(userEntity.getUserName() + ",");
							}
						}
					}
				}

			}
			if (!StringUtils.isEmpty(sb.toString())) {
				response.setSuccess(false);
				response.setResultMessage("用户" + sb.toString() + "存在于" + project.getProjectName() + "其它项目组中!");
				return response;
			}
			Long salesGroupId = null;
			if (salesGroupDto != null && salesGroupDto.getId() != null) {
				salesGroupDto.setUpdateUserId(user.getId());
				salesGroupDto.setUpdateTime(new Date());
				salesGroupService.update(salesGroupDto);
				salesGroupId = salesGroupDto.getId();
			} else {
				salesGroupDto.setCreateUserId(user.getId());
				salesGroupDto.setCreateTime(new Date());
				salesGroupDto.setUpdateUserId(user.getId());
				salesGroupDto.setUpdateTime(new Date());
				salesGroupDto.setDelFlag("0");

				salesGroupDto.setProjectCode(project.getProjectCode());
				salesGroupDto.setMerchantId(user.getMerchantId());
				salesGroupDto.setAccessCode(project.getAccessCode());
				salesGroupDto.setUserCode(user.getUserCode());
				SalesGroupDto createDto = salesGroupService.create(salesGroupDto);
				salesGroupId = createDto.getId();
			}
			//销售组信息
			SalesGroup salesGroup = salesGroupService.selectById(salesGroupId);
			/**
			 * 查询原先销售组中的所有成员
			 * @author ny
			 * date 2017-02-23
			 */
			//查询用户新分配到项目组数据
			for (SalesGroupUserDto entityDto : userDto) {
				SalesGroupUserDto dto_update = new SalesGroupUserDto();
				dto_update.setSalesGroupId(salesGroupId);
				dto_update.setUserId(entityDto.getUserId());
				dto_update.setStatus("0");
				SalesGroupUser sguEntity = service.selectByDto(dto_update);
				if(sguEntity == null){
					Map<String, String> jsonMap = new HashMap<String, String>();
					jsonMap.put("name", "项目组变更");
					jsonMap.put("projectId", String.valueOf(project.getId()));//项目Id
					jsonMap.put("projectName", project.getProjectName());//项目名称
					jsonMap.put("pushStatus", entityDto.getStatus());//状态：0 正常，1 已关闭
					JSONObject jsonObject = (JSONObject) JSONObject.toJSON(jsonMap);
					String json = jsonObject.toString();
					Map<String, String> map = new HashMap<String, String>();
					map.put("Data", json);
					map.put("pushType", "xmzbg");//项目组变更推送固定类型值
					//接收push消息
					String text = "您所在的项目组：["+salesGroup.getName()+"]，发生变更";
					appPushService.pushMessage(String.valueOf(entityDto.getUserId()), text, null, map);//用户所在项目组数据变动
				}
				
			}
			//查询项目组原用户信息
			SalesGroupUserDto dto = new SalesGroupUserDto();
			dto.setSalesGroupId(salesGroupId);
			List<SalesGroupUser> salesGroupUserEntity = service.selectListByDto(dto);
			// 先删除销售组中的所有成员
			SalesGroupUserDto deleteDto = new SalesGroupUserDto();
			deleteDto.setSalesGroupId(salesGroupId);
			deleteDto.setDelFlag("0");
			service.destroy(deleteDto);
			// 新增
			for (SalesGroupUserDto listDto : userDto) {
				listDto.setSalesGroupId(salesGroupId);
				listDto.setMerchantId(user.getMerchantId());
				listDto.setAccessCode(project.getAccessCode());
				listDto.setUserCode(user.getUserCode());
				listDto.setCreateUserId(user.getId());
				listDto.setCreateTime(new Date());
				listDto.setUpdateUserId(user.getId());
				listDto.setUpdateTime(new Date());
				listDto.setDelFlag("0");
				service.create(listDto);
				CustomerDto entity = new CustomerDto();
				entity.setUserCode(userService.selectById(listDto.getUserId()).getUserCode());
				entity.setMerchantId(user.getMerchantId());
				entity.setSalesGroupId(salesGroupId);
				entity.setProjectId(salesGroupDto.getProjectId());
				// 更新已移除的销售组成员下的客户信息
				if (listDto.getStatus().equals("1")) {
					entity.setNewSalesGroupId(null);
				} else if (listDto.getStatus().equals("0")) {
					entity.setNewSalesGroupId(salesGroupId.toString());
				}
				customerService.updateBySaleGroupUser(entity);
				
				/**
				 * 项目组用户设置消息推送
				 * @author ny
				 * date 2017-02-23
				 */
				for(SalesGroupUser sgu : salesGroupUserEntity){
					String userId = null;
					String projectId = null;
					String projectName = null;
					String pushStatus = null;
					//获取销售组信息
					if(salesGroupDto.getId() != null){
						if(String.valueOf(sgu.getUserId()).equals(String.valueOf(listDto.getUserId())) && !sgu.getStatus().equals(listDto.getStatus())){
							userId = String.valueOf(listDto.getUserId());
							projectId = String.valueOf(project.getId());
							projectName = project.getProjectName();
							pushStatus = listDto.getStatus();
						}
					/*}else{
						userId = String.valueOf(listDto.getUserId());
						projectId = String.valueOf(project.getId());
						projectName = project.getProjectName();
						pushStatus = listDto.getStatus();*/
					}
					if(userId != null){
						Map<String, String> jsonMap = new HashMap<String, String>();
						jsonMap.put("name", "项目组变更");
						jsonMap.put("projectId", projectId);//项目Id
						jsonMap.put("projectName", projectName);//项目名称
						jsonMap.put("pushStatus", pushStatus);//状态：0 正常，1 已关闭
						JSONObject jsonObject = (JSONObject) JSONObject.toJSON(jsonMap);
						String json = jsonObject.toString();
						Map<String, String> map = new HashMap<String, String>();
						map.put("Data", json);
						map.put("pushType", "xmzbg");//项目组变更推送固定类型值
						//接收push消息
						String text = "您所在的项目组：["+salesGroup.getName()+"]，发生变更";
						appPushService.pushMessage(userId, text, null, map);//用户所在项目组数据变动
					}
				}
			}
			
			response.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	public List<Long> removeDuplicate(List<SalesGroupUserDto> list) {
		List<Long> array = new ArrayList<>();
		for (int i = 0; i < list.size() - 1; i++) {
			for (int j = list.size() - 1; j > i; j--) {
				if(list.get(j).getStatus().equals("0")&&list.get(i).getStatus().equals("0")){
				if (list.get(j).getUserId().compareTo(list.get(i).getUserId()) == 0) {
						array.add(list.get(i).getUserId());
					}
					
				}
			}
		}
		return array;
	}

	@Override
	public Page<SalesGroupUserDto> findSalesGroupUserDto(SalesGroupUserDto dto, Integer begin, Integer row) {
		Page<SalesGroupUserDto> response = new Page<SalesGroupUserDto>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<SalesGroupUser> page = service.getPageModel(dto, begin, row);
			response.setTotal(page.getTotal());
			response.setTotalPages(page.getTotalPages());
			response.setPageSize(page.getPageSize());
			response.setPageNumber(page.getPageNumber());
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			} else {
				List<SalesGroupUserDto> salesList = new ArrayList<SalesGroupUserDto>();
				for (SalesGroupUser user : page.getRows()) {
					User obj = userService.selectById(user.getUserId());
					if (null == obj)
						continue;
					SalesGroupUserDto addDto = new SalesGroupUserDto();
					BeanUtils.copyProperties(user, addDto);
					addDto.setUserCN(obj.getUserName());
					// 0正常 1已移除
					if (user.getStatus().equals("0")) {
						addDto.setStatusCN("正常");
					} else if (user.getStatus().equals("1")) {
						addDto.setStatusCN("已移除");
					}
					salesList.add(addDto);
				}
				response.setRows(salesList);
			}
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	public ResponseList<SalesGroupUser> findAssignedSalesGroupByDto(SalesGroupUserDto dto) {
		ResponseList<SalesGroupUser> response = new ResponseList<SalesGroupUser>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			if (!StringUtils.isEmpty(dto.getResourcesCode())) {
				String roleDataAuthorityValue = dataPermissionService.roleDataAuthorityValue(dto.getPermissionUserId(),
						dto.getResourcesCode());
				if (roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_00.getNo())) {
					// 当数据权限为无时 返回空的list
					response.success(new ArrayList<SalesGroupUser>());
					return response;
				} else if (roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_01.getNo())) {
					// 当数据权限为个人时
					dto.setDataPermission(" AND t.user_id=" + dto.getPermissionUserId());
				} else {
					// 当数据权限为全部、项目组、销售组时则不需要过滤，直接跳过
				}
			}

			List<SalesGroupUser> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

}
